package com.cicc.beergamevirtualsimulationsystem.common.webSocket.config;

import com.cicc.beergamevirtualsimulationsystem.common.webSocket.WebSocketHandler;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.handler.JsonMessageHandler;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.handler.impl.*;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.holder.JsonMessageHandlerHolder;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.interceptor.WebSocketInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {  

    private final WebSocketHandler countdownWebSocketHandler;
    private final ApplicationContext applicationContext;

    public WebSocketConfig(WebSocketHandler countdownWebSocketHandler ,ApplicationContext applicationContext) {
        this.countdownWebSocketHandler = countdownWebSocketHandler;
        this.applicationContext = applicationContext;
    }  

    @Override  
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {  
        registry.addHandler(countdownWebSocketHandler, "/api/link/{id}/{roomId}")
                .addInterceptors(new WebSocketInterceptor())
                .setAllowedOrigins("*"); // 允许所有跨域请求，生产环境中应配置为具体允许的域名
    }

    @Bean
    public void registerMessageHandlers() {
        String[] handlerNames = applicationContext.getBeanNamesForType(JsonMessageHandler.class);
        for (String name : handlerNames) {
            JsonMessageHandler handler = applicationContext.getBean(name, JsonMessageHandler.class);
            JsonMessageHandlerHolder.addHandler(handler);
        }
//        JsonMessageHandlerHolder.addHandler(new PingJsonMessageHandler());
//        //初始化房间
//        JsonMessageHandlerHolder.addHandler(new InitRoomJsonMessageHandler());
//        //选择角色
//        JsonMessageHandlerHolder.addHandler(new SelectRoleJsonMessageHandler());
//        // 开始游戏
//        JsonMessageHandlerHolder.addHandler(new StartJsonMessageHandler());
//        //统计房间人数
//        JsonMessageHandlerHolder.addHandler(new PlayerCountJsonMessageHandler());
//        //房间解散
//        JsonMessageHandlerHolder.addHandler(new GameRoomDismissJsonMessageHandler());

    }

}
